package com.job.client.gateway.filter;

import com.job.client.common.result.AppHttpCode;
import com.job.client.common.result.ResponseResult;
import com.job.client.common.utils.JwtTokenUtils;
import com.job.client.model.auth.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getRawPath();
        String pattern = "/api/v1/client/auth/.*";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(url);
        if(m.matches()){ //放行/api/v1/client/auth开头的路径
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("Authorization");
        if(token == null || "".equals(token)){
            log.error("用户未登录");
            return Mono.error(new RuntimeException("用户未登录"));
        }
        User user = JwtTokenUtils.checkToken(token);
        // 其中有数据缺失则表示token被修改
        if(user.getUserId()==null || (user.getUsername()==null && user.getPhone()==null)){
            log.error("用户非法访问");
            return Mono.error(new RuntimeException("用户非法访问"));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
